import api from "@/store/api/index.js";
import { createSlice } from "@reduxjs/toolkit";
export const storeSlice = createSlice({
  name: "store", //标志action中type的前缀
  initialState: {
    list: null,
  },
  reducers: {
    //操作state的各种方法
    // 获取store列表
    getStoreList(state, action) {
      state.list = action.payload;
    },
    // 移除收藏列表的某一项
    // action传一个id ，循环list找到id对应的项移除
    removeStore(state, action) {
      if (Array.isArray(state.list)) {
        state.list = state.list.filter((item) => {
          return +item.id !== +action.payload;
        });
      }
    },
    // 清空收藏列表
    clearStoreList(state) {
      state.list = null;
    },
  },
});
export const { getStoreList, removeStore, clearStoreList } = storeSlice.actions;
export const getStoreListAsync = () => {
  return async (dispatch) => {
    let list = [];
    try {
      let { code, data } = await api.storeList();
      if (code === 0) {
        list = data;
      }
    } catch (_) {}
    dispatch(getStoreList(list));
  };
};
